<template>
  <div class="pane-account">
    <el-form
      :model="account"
      label-width="70px"
      style="max-width: 600px"
      :rules="accountRules"
      ref="formRef"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>
  
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormRules } from 'element-plus'
import type { ElForm } from 'element-plus'
import { ElMessage } from 'element-plus'
import { accountLoginRequest } from '@/service/login/login'
import useLoginStore from '@/store/login/login'
import type { IAccount } from '@/types/login'
import { localCache } from '@/utils/cache'
const account = reactive<IAccount>({
  name: localCache.getCache('CACHE_NAME') ?? '',
  password: localCache.getCache('CACHE_PASSWORD') ?? ''
})
const CACHE_NAME = 'name'
const CACHE_PASSWORD = 'password'

const accountRules: FormRules = {
  name: [
    { required: true, message: '不能为空', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{6,10}$/,
      message: '长度在 6 到 10 个字符',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '不能为空', trigger: 'blur' },
    {
      pattern: /^[a-z0-9]{6,10}$/,
      message: '长度在 6 到 10 个字符',
      trigger: 'blur'
    }
  ]
}
//添加登录逻辑，不符合校验规则的输入不生效
const formRef = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()
function loginAction(isRemPwd: boolean) {//传入的是记住的密码状态
  formRef.value?.validate((valid) => {
    if (valid) {
      const name = account.name
      const password = account.password
      //向服务器发送网络请求,登录成功之后，将账号密码保存到本地存储中
      loginStore.loginAccountAction({ name, password }).then((res) => {
        if (isRemPwd) {
          localCache.setCache('CACHE_NAME', name)
          localCache.setCache('CACHE_PASSWORD', password)
        } else {
          localCache.removeCache('CACHE_NAME')
          localCache.removeCache('CACHE_PASSWORD')
        }
      })
    } else {
      ElMessage.primary('请按格式输入账号和密码')
    }
  })
}
defineExpose({ loginAction })
</script>
  
  <style lang="less" scoped>
.pane-account {
  width: 100%;
  height: 100%;
}
</style>